﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using ThoughtWorks.QRCode.Codec ;
using CrystalDecisions.CrystalReports.Engine;

namespace 提交管理平台V1
{
    public partial class frmLabelPrint : Form
    {
        UserInfo ui;

        DataTable dt;
        DataTable dtPrinterSettings;

        DataGridViewSelectedCellCollection DataGridClipBoard;

        SqlTools sqt;

        public frmLabelPrint(DataTable tmpdt, UserInfo tmpui)
        {
            InitializeComponent();
            dt = tmpdt;
            ui = tmpui;
            this.WindowState = FormWindowState.Maximized;
        }

        private void frmLabelPrint_Load(object sender, EventArgs e)
        {
            sqt = new SqlTools(GeneralTools.GetConnectionString(提交管理平台V1.Properties.Settings.Default.Host, "DefualtDataBase"));
            BuildDataTable();
            cmbPrintMode.SelectedIndex = 0;
            iniPrinterSettings();
            iniComboBox();
        }

        private void iniComboBox()
        {
            cmbNbq.Items.Clear();
            cmbWbq.Items.Clear();
            foreach (string strFileName in Directory.GetFiles(Application.StartupPath + "\\Template\\Special\\", "内标签_*.rpt"))
            {
                FileInfo fi = new FileInfo(strFileName);
                cmbNbq.Items.Add(fi.Name.Substring(0, fi.Name.Length - 4));
            }
            foreach (string strFileName in Directory.GetFiles(Application.StartupPath + "\\Template\\Special\\", "外标签_*.rpt"))
            {
                FileInfo fi = new FileInfo(strFileName);
                cmbWbq.Items.Add(fi.Name.Substring(0, fi.Name.Length - 4));
            }
            if (cmbNbq.Items.Count > 0)
            {
                cmbNbq.SelectedIndex = 0;
            }
            if (cmbWbq.Items.Count > 0)
            {
                cmbWbq.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 建立datagridview的数据源
        /// </summary>
        private void BuildDataTable()
        {
            DataTable tmpdt = new DataTable();
            tmpdt.Columns.Add("外标签数量");
            tmpdt.Columns.Add("外标签张数");
            tmpdt.Columns.Add("内标签数量");
            tmpdt.Columns.Add("内标签张数");
            tmpdt.Columns.Add("型号规格");
            tmpdt.Columns.Add("执行标准");
            tmpdt.Columns.Add("生产批号");
            tmpdt.Columns.Add("生产日期");
            tmpdt.Columns.Add("合同号");
            tmpdt.Columns.Add("提交数量");
            tmpdt.Columns.Add("淘汰率");
            tmpdt.Columns.Add("筛选数量");
            tmpdt.Columns.Add("包装员");
            tmpdt.Columns.Add("包装日期");
            tmpdt.Columns.Add("编带", typeof(bool));
            tmpdt.Columns.Add("备注");
            tmpdt.Columns.Add("提交时间");
            tmpdt.Columns.Add("质量等级");
            tmpdt.Columns.Add("补充协议");
            tmpdt.Columns.Add("订单编号");
            tmpdt.Columns.Add("订单项次");
            tmpdt.Columns.Add("提交序号");
            tmpdt.Columns.Add("客户规格");
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    DataRow r = tmpdt.NewRow();
                    r["外标签数量"] = dt.Rows[i]["提交数量"];
                    r["外标签张数"] = 1;
                    r["内标签数量"] = GetPackingQuantity(GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty), GeneralTools.GetString(dt.Rows[i]["型号"], string.Empty), GeneralTools.GetString(dt.Rows[i]["尺寸"], string.Empty), GeneralTools.GetBoolean(dt.Rows[i]["编带"], false));
                    r["编带"] = GeneralTools.GetBoolean(dt.Rows[i]["编带"], false);
                    if (GeneralTools.GetInt(r["内标签数量"], 0) == 0)
                    {
                        r["内标签张数"] = 0;
                    }
                    else
                    {
                        try
                        {
                            r["内标签张数"] = Math.Ceiling(GeneralTools.GetDouble(dt.Rows[i]["提交数量"], 0d) / GeneralTools.GetDouble(r["内标签数量"], 0d));
                        }
                        catch
                        {
                            r["内标签张数"] = 0;
                        }
                    }
                    if (GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty).Equals(string.Empty) || GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty).Equals("GJB"))
                    {
                        r["型号规格"] = GeneralTools.GetString(dt.Rows[i]["型号"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["尺寸"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["特性"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["电压"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["容量"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["引出端形式"], string.Empty);
                    }
                    else if (GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty).Equals("M"))
                    {
                        #region 检查客户编号是否765厂，如果是，则去除工业级标识
                        string strTmpSelect = "select hta003 客户编号,hta004 客户名称 from TPAMain.dbo.hta_table where hta001='@订单编号'";
                        DataTable tmpdt2 = sqt.GetData(strTmpSelect.Replace("@订单编号", GeneralTools.GetString(dt.Rows[i]["订单编号"], string.Empty)));
                        if (tmpdt2 != null && tmpdt2.Rows.Count > 0 && GeneralTools.GetString(tmpdt2.Rows[0]["客户编号"], string.Empty).StartsWith("765"))
                        {
                            r["型号规格"] = GeneralTools.GetString(dt.Rows[i]["型号"], string.Empty) + "-" +
                                                        GeneralTools.GetString(dt.Rows[i]["尺寸"], string.Empty) + "-" +
                                                        GeneralTools.GetString(dt.Rows[i]["特性"], string.Empty) + "-" +
                                                        GeneralTools.GetString(dt.Rows[i]["电压"], string.Empty) + "-" +
                                                        GeneralTools.GetString(dt.Rows[i]["容量"], string.Empty) + "-" +
                                                        GeneralTools.GetString(dt.Rows[i]["引出端形式"], string.Empty);
                        }
                        else
                        {
                            r["型号规格"] = GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty) + " " +
                                                    GeneralTools.GetString(dt.Rows[i]["型号"], string.Empty) + "-" +
                                                    GeneralTools.GetString(dt.Rows[i]["尺寸"], string.Empty) + "-" +
                                                    GeneralTools.GetString(dt.Rows[i]["特性"], string.Empty) + "-" +
                                                    GeneralTools.GetString(dt.Rows[i]["电压"], string.Empty) + "-" +
                                                    GeneralTools.GetString(dt.Rows[i]["容量"], string.Empty) + "-" +
                                                    GeneralTools.GetString(dt.Rows[i]["引出端形式"], string.Empty);
                        }
                        #endregion 
                    }
                    else
                    {
                        r["型号规格"] = "\"" + GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty) + "\" " +
                                                GeneralTools.GetString(dt.Rows[i]["型号"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["尺寸"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["特性"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["电压"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["容量"], string.Empty) + "-" +
                                                GeneralTools.GetString(dt.Rows[i]["引出端形式"], string.Empty);
                    }
                    while (GeneralTools.GetString(r["型号规格"], string.Empty).Contains("--"))
                    {
                        r["型号规格"] = GeneralTools.GetString(r["型号规格"], string.Empty).Replace("--", "-");
                    }
                    while (GeneralTools.GetString(r["型号规格"], string.Empty).EndsWith("-"))
                    {
                        r["型号规格"] = GeneralTools.GetString(r["型号规格"], string.Empty).Substring(0, GeneralTools.GetString(r["型号规格"], string.Empty).Length - 1);
                    }
                    if (GeneralTools.GetString(dt.Rows[i]["执行标准"], string.Empty).Contains(" "))
                    {
                        string[] strTmp = GeneralTools.GetString(dt.Rows[i]["执行标准"], string.Empty).Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        if (strTmp.Length > 0)
                        {
                            r["执行标准"] = strTmp[0];
                        }
                        else
                        {
                            r["执行标准"] = string.Empty;
                        }
                        if (strTmp.Length > 1)
                        {
                            r["备注"] = GeneralTools.GetString(dt.Rows[i]["执行标准"], string.Empty).Split(' ').GetValue(1).ToString();
                        }
                        else
                        {
                            r["备注"] = string.Empty;
                        }
                    }
                    else
                    {
                        r["执行标准"] = dt.Rows[i]["执行标准"];
                        r["备注"] = string.Empty;
                    }
                    r["补充协议"] = dt.Rows[i]["附加协议"];
                    r["订单编号"] = dt.Rows[i]["订单编号"];
                    r["订单项次"] = dt.Rows[i]["订单项次"];
                    r["提交序号"] = dt.Rows[i]["序号"];
                    if (!GeneralTools.GetString(r["补充协议"], string.Empty).Equals(string.Empty))
                    {
                        r["备注"] = GeneralTools.GetString(r["补充协议"], string.Empty) + "   ";
                    }
                    if ((!GeneralTools.GetString(dt.Rows[i]["备注"], string.Empty).Equals(string.Empty)) &&
                        (!GeneralTools.GetString(dt.Rows[i]["备注"], string.Empty).StartsWith("J-")) &&
                        (!GeneralTools.GetString(dt.Rows[i]["备注"], string.Empty).StartsWith("M-")))
                    {
                        r["备注"] = GeneralTools.GetString(r["备注"], string.Empty) + GeneralTools.GetString(dt.Rows[i]["备注"], string.Empty);
                    }
                    r["生产批号"] = dt.Rows[i]["批号"];
                    try
                    {
                        r["生产日期"] = Convert.ToDateTime(dt.Rows[i]["生产日期"]).ToString("yyyy-MM-dd");
                    }
                    catch
                    {
                        r["生产日期"] = dt.Rows[i]["生产日期"];
                    }
                    r["合同号"] = dt.Rows[i]["合同号"];
                    r["提交数量"] = dt.Rows[i]["提交数量"];
                    r["淘汰率"] = dt.Rows[i]["淘汰率"];
                    r["筛选数量"] = dt.Rows[i]["筛选数量"];
                    r["包装员"] = dt.Rows[i]["包装员"];
                    r["包装日期"] = DateTime.Now.ToString("yyyy-MM");
                    r["提交时间"] = dt.Rows[i]["提交时间"];
                    if (dt.Rows[i]["质量等级"].Equals("M") || GeneralTools.GetString(dt.Rows[i]["质量等级"], string.Empty).Equals(string.Empty))
                    {
                        r["质量等级"] = "M";
                    }
                    else
                    {
                        r["质量等级"] = dt.Rows[i]["质量等级"];
                    }
                    #region 判断客户名称或编号，在备注中带出客户信息
                    if (!GeneralTools.GetString(dt.Rows[i]["订单编号"], string.Empty).Equals(string.Empty) && (!GeneralTools.GetString(dt.Rows[i]["订单编号"], string.Empty).Equals(string.Empty)))
                    {
                        string strTmpSelect2 = "select hta003 客户编号,hta004 客户名称,htb027 用户物料号 from TPAMain.dbo.hta_table,TPAMain.dbo.htb_table where htb001='@订单编号' and htb002=@订单项次 and hta001=htb001";
                        DataTable tmpdt3 = sqt.GetData(strTmpSelect2.Replace("@订单编号", GeneralTools.GetString(dt.Rows[i]["订单编号"], string.Empty))
                                                                                                .Replace("@订单项次", GeneralTools.GetString(dt.Rows[i]["订单项次"], string.Empty)));
                        //上海航空电器，在备注中带出客户物料代码
                        if (tmpdt3 != null && tmpdt3.Rows.Count > 0 && GeneralTools.GetString(tmpdt3.Rows[0]["客户名称"], string.Empty).Contains("上海航空电器"))
                        {
                            r["备注"] = GeneralTools.GetString(r["备注"], string.Empty) + " 用户物料号：" + GeneralTools.GetString(tmpdt3.Rows[0]["用户物料号"], string.Empty);
                        }
                        //08-10所带出客户订单号
                        if (tmpdt3 != null && tmpdt3.Rows.Count > 0 && GeneralTools.GetString(tmpdt3.Rows[0]["客户编号"], string.Empty).StartsWith("08-10"))
                        {
                            r["备注"] = GeneralTools.GetString(r["备注"], string.Empty) + " 客户订单号：" + GeneralTools.GetString(tmpdt3.Rows[0]["用户物料号"], string.Empty);
                        }
                        //33所、飞航物资供应站带出采购文件编号
                        if (tmpdt3 != null && tmpdt3.Rows.Count > 0 &&
                            (GeneralTools.GetString(tmpdt3.Rows[0]["客户编号"], string.Empty).StartsWith("06-33") ||
                            (GeneralTools.GetString(tmpdt3.Rows[0]["客户名称"], string.Empty).Contains("科工飞航"))))
                        {
                            r["备注"] = GeneralTools.GetString(r["备注"], string.Empty) + " 采购文件编号：" + GeneralTools.GetString(tmpdt3.Rows[0]["用户物料号"], string.Empty);
                        }
                        //08-14所，根据出库单型号规格查询客户规格
                        if (tmpdt3 != null&&
                            (!GeneralTools.GetString(dt.Rows[i]["出库单号"], string.Empty).Equals(string.Empty)) && 
                            tmpdt3.Rows.Count > 0 && 
                            GeneralTools.GetString(tmpdt3.Rows[0]["客户编号"], string.Empty).StartsWith("08-14") &&
                            (!GeneralTools.GetString(tmpdt3.Rows[0]["客户名称"], string.Empty).Equals ("中电科技（南京）电子信息发展有限公司"))
                            )
                        {
                            string strTmpSelect3 = "select CustomerModel from TPAMain .dbo .gxck_table left join CustomerMaterialNoMapping on MyModel collate Chinese_PRC_BIN=gxck012 where gxck001='@出库单号' and CustomerID='08-14'";
                            string strCustomerModel = GeneralTools.GetString(sqt.DoCmdScalarData(strTmpSelect3.Replace("@出库单号", GeneralTools.GetString(dt.Rows[i]["出库单号"], string.Empty))),string.Empty );
                            if (strCustomerModel ==string.Empty )
                            {
                                GeneralTools.ShowWarningMsg("第" + (i + 1).ToString() + "项未获取到14所型号规格，请联系市场部内勤添加客户型号规格信息！");
                            }
                            else
                            {
                                r["客户规格"] = strCustomerModel;
                            }
                        }
                    }
                    #endregion
                    tmpdt.Rows.Add(r);
                }
            }
            dgv1.DataSource = tmpdt;
            dgv1.AutoResizeColumns();
            dgv1.Columns["质量等级"].Visible = false;
            CheckDataToChangeColor();
        }

        private DataTable GetReportData_w(DataRow tmpdr)
        {
            DataTable tmpdt_w = new DataTable();
            tmpdt_w.TableName = "ReportData";
            tmpdt_w.Columns.Add("型号规格");
            tmpdt_w.Columns.Add("客户规格");
            tmpdt_w.Columns.Add("执行标准");
            tmpdt_w.Columns.Add("生产批号");
            tmpdt_w.Columns.Add("生产日期");
            tmpdt_w.Columns.Add("合同号");
            tmpdt_w.Columns.Add("数量");
            tmpdt_w.Columns.Add("备注");
            tmpdt_w.Columns.Add("包装员");
            tmpdt_w.Columns.Add("二维码", typeof(System.Byte[]));
            tmpdt_w.Columns.Add("包装日期");
            int iCount = GeneralTools.GetInt(tmpdr["提交数量"], 0);        //总数量
            int iP = GeneralTools.GetInt(tmpdr["外标签数量"], 0);     //外标签数量
            int iPCount = GeneralTools.GetInt(tmpdr["外标签张数"], 0);        //外标签张数
            while (iCount > 0 && iP > 0 && iPCount > 0)
            {
                DataRow r = tmpdt_w.NewRow();
                r["客户规格"] = tmpdr["客户规格"];
                r["型号规格"] = tmpdr["型号规格"];
                r["执行标准"] = tmpdr["执行标准"];
                r["生产批号"] = tmpdr["生产批号"];
                r["生产日期"] = tmpdr["生产日期"];
                r["合同号"] = tmpdr["合同号"];
                if (iCount < iP)
                {
                    r["数量"] = iCount;
                }
                else
                {
                    r["数量"] = iP;
                }
                iCount -= iP;
                iPCount--;
                r["备注"] = tmpdr["备注"];
                //r["包装员"] = Properties.Settings.Default.外包装包装员;
                r["包装员"] = ui.GetUserSetting("外包装包装员");
                //获取客户编号、客户名称
                DataTable dtCustomer = sqt.GetData("select hta003 客户编号,hta004 客户名称 from TPAMain.dbo.hta_table where hta001='" + GeneralTools.GetString(tmpdr["订单编号"], string.Empty) + "'");
                string strTmpCustomerID = string.Empty;
                string strTmpCustomerName = string.Empty;
                if (dtCustomer.Rows.Count > 0)
                {
                    strTmpCustomerID = GeneralTools.GetString(dtCustomer.Rows[0]["客户编号"], string.Empty);
                    strTmpCustomerName = GeneralTools.GetString(dtCustomer.Rows[0]["客户名称"], string.Empty);
                }
                string strTmp = string.Empty;
                if (strTmpCustomerName == "北京自动化控制设备研究所" || strTmpCustomerName.StartsWith("中国航天科工飞航技术研究院"))
                {
                    #region 打印33所指定二维码
                    string strTmpSelect = "select hta003 客户编号,hta004 客户名称,htb027 用户物料号 from TPAMain.dbo.hta_table,TPAMain.dbo.htb_table where htb001='@订单编号' and htb002=@订单项次 and hta001=htb001";
                    DataTable tmpdt_33 = sqt.GetData(strTmpSelect.Replace("@订单编号", GeneralTools.GetString(tmpdr["订单编号"], string.Empty))
                                                                                              .Replace("@订单项次", GeneralTools.GetString(tmpdr["订单项次"], string.Empty)));
                    if (tmpdt_33.Rows.Count > 0)
                    {
                        string strPurchaseNo = GeneralTools.GetString(tmpdt_33.Rows[0]["用户物料号"], string.Empty);
                        string strSN = GeneralTools.GetString(tmpdr["生产批号"], string.Empty).Trim();
                        string strScrq = GeneralTools.GetString(tmpdr["生产日期"], string.Empty).Trim().Replace("-", "");
                        strTmp = "<?xml version=\"1.0\" encoding=\"GBK\"?><TX><CBH>" + strPurchaseNo + "</CBH><PC>" + strSN + "</PC><SCRQ>" + strScrq + "</SCRQ><YL1></YL1><YL2></YL2></TX>";
                        if (strPurchaseNo.Equals(string.Empty))
                        {
                            GeneralTools.ShowInfoMsg("订单中未包含33所订单ID信息，请联系市场部内务处理！");
                        }
                    }
                    #endregion
                }
                else
                {
                    strTmp = GeneralTools.GetString(tmpdr["型号规格"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["执行标准"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["生产批号"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["生产日期"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["合同号"], string.Empty) + "|" +
                                GeneralTools.GetString(r["数量"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["淘汰率"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["筛选数量"], string.Empty) + "|" +
                                GeneralTools.GetString(tmpdr["备注"], string.Empty);
                }
                //二维码
                try
                {
                    QRCodeEncoder qc = new QRCodeEncoder();
                    qc.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                    //Size
                    qc.QRCodeScale = 4;
                    //Version
                    if (strTmp.Length >120)
                    {
                        qc.QRCodeVersion = 10;
                    }
                    else if(strTmp .Length >110)
                    {
                        qc.QRCodeVersion = 9;
                    }
                    else if (strTmp.Length > 100)
                    {
                        qc.QRCodeVersion = 8;
                    }
                    else
                    {
                        qc.QRCodeVersion = 7;
                    }
                    //CorrectLevel
                    qc.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                    Image image = qc.Encode(strTmp);
                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                    r["二维码"] = ms.GetBuffer();
                }
                catch (Exception ex)
                {
                    GeneralTools.ShowErrorMsg("生产二维码错误：" + ex.Message);
                }
                //r["包装日期"] = DateTime.Now.ToString("yyyy-MM");
                r["包装日期"] = tmpdr["包装日期"];
                tmpdt_w.Rows.Add(r);
            }
            return tmpdt_w;
        }

        /// <summary>
        /// 获取43所二维码外标签数据源
        /// </summary>
        /// <param name="tmpdr">原始数据</param>
        /// <returns>标签数据</returns>
        private DataTable GetReportData_w_43(DataRow tmpdr)
        {
            DataTable tmpdt_w = new DataTable();
            tmpdt_w.TableName = "ReportData";
            tmpdt_w.Columns.Add("物料编码");
            tmpdt_w.Columns.Add("物料名称");
            tmpdt_w.Columns.Add("型号");
            tmpdt_w.Columns.Add("质量等级");
            tmpdt_w.Columns.Add("防静电等级");
            tmpdt_w.Columns.Add("采购订单");
            tmpdt_w.Columns.Add("发货数量");
            tmpdt_w.Columns.Add("生产批次");
            tmpdt_w.Columns.Add("计划行号");
            tmpdt_w.Columns.Add("申购部门");
            tmpdt_w.Columns.Add("采购员");
            tmpdt_w.Columns.Add("检验代码");
            tmpdt_w.Columns.Add("二维码", typeof(Byte[]));
            tmpdt_w.Columns.Add("备注");
            DataRow r = tmpdt_w.NewRow();
            r["物料编码"] = string.Empty;
            r["物料名称"] = string.Empty;
            r["型号"] = tmpdr["型号规格"];
            r["质量等级"] = tmpdr["质量等级"];
            r["防静电等级"] = string.Empty;
            r["采购订单"] = string.Empty;
            r["发货数量"] = tmpdr["提交数量"];
            r["生产批次"] = tmpdr["生产批号"];
            r["计划行号"] = string.Empty;
            r["申购部门"] = string.Empty;
            r["采购员"] = string.Empty;
            r["检验代码"] = string.Empty;
            r["备注"] = string.Empty;
            //二维码字符串
            string strTmp = string.Empty;
            //采购订单，长度20位，#DD开头，不足位后补@
            string strTmpOrderID = "#DD" + r["采购订单"].ToString();
            strTmp += strTmpOrderID.PadRight(20, '@');
            //物料编码，长度20位，#WL开头，不足位后补@
            string strTmpMaterialID = "#WL" + r["物料编码"].ToString();
            strTmp += strTmpMaterialID.PadRight(20, '@');
            //计划行号，长度20位，#JH开头，不足位后补@
            string strTmpJHID = "#JH" + r["计划行号"].ToString();
            strTmp += strTmpJHID.PadRight(20, '@');
            //生产批次，长度20位，#SP开头，不足位后补@，超过20位截取后20位
            string strTmpSCNo = "#SP" + r["生产批次"].ToString();
            strTmp += strTmpSCNo.PadRight(20, '@');
            //送货数量，长度20位，小数点后保留2位，#SL开头，不足位前补@
            string strTmpSL = "#SL" + Convert.ToInt32(r["发货数量"]).ToString("0.00").PadLeft(17, '@');
            strTmp += strTmpSL;
            //二维码
            try
            {
                QRCodeEncoder qc = new QRCodeEncoder();
                qc.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
                //Size
                qc.QRCodeScale = 4;
                //Version
                qc.QRCodeVersion = 9;
                //CorrectLevel
                qc.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.M;
                Image image = qc.Encode(strTmp);
                System.IO.MemoryStream ms = new System.IO.MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
                r["二维码"] = ms.GetBuffer();
            }
            catch (Exception ex)
            {
                GeneralTools.ShowErrorMsg("生产二维码错误：" + ex.Message);
            }
            tmpdt_w.Rows.Add(r);
            return tmpdt_w;
        }


        private DataTable GetReportData_n_qz(DataRow tmpdr)
        {
            DataTable tmpdt_n = new DataTable();
            tmpdt_n.TableName = "ReportData";
            tmpdt_n.Columns.Add("型号规格");
            tmpdt_n.Columns.Add("执行标准");
            tmpdt_n.Columns.Add("生产批号");
            tmpdt_n.Columns.Add("生产日期");
            tmpdt_n.Columns.Add("合同号");
            tmpdt_n.Columns.Add("数量");
            tmpdt_n.Columns.Add("淘汰率");
            tmpdt_n.Columns.Add("筛选数量");
            tmpdt_n.Columns.Add("备注");
            tmpdt_n.Columns.Add("包装员");
            tmpdt_n.Columns.Add("客户规格");
            int iCount = GeneralTools.GetInt(tmpdr["提交数量"], 0);        //总数量
            int iP = GeneralTools.GetInt(tmpdr["内标签数量"], 0);             //内标签数量
            int iPCount = GeneralTools.GetInt(tmpdr["内标签张数"], 0);    //内标签张数
            while (iCount > 0 && iP > 0 && iPCount > 0)
            {
                DataRow r = tmpdt_n.NewRow();
                //if (GeneralTools.GetString(tmpdr["型号规格"], string.Empty).StartsWith("M-"))
                //{
                //    r["型号规格"] = GeneralTools.GetString(tmpdr["型号规格"], string.Empty).Substring(2);
                //}
                //else
                //{
                //    r["型号规格"] = tmpdr["型号规格"];
                //}
                //while (GeneralTools.GetString(r["型号规格"], string.Empty).Contains("--"))
                //{
                //    r["型号规格"] = GeneralTools.GetString(r["型号规格"], string.Empty).Replace("--", "-");
                //}
                //while (GeneralTools.GetString(r["型号规格"], string.Empty).EndsWith ("-"))
                //{
                //    r["型号规格"] = GeneralTools.GetString(r["型号规格"], string.Empty).Substring(0, GeneralTools.GetString(r["型号规格"], string.Empty).Length - 1);
                //}
                //if (GeneralTools.GetString(r["型号规格"], string.Empty).StartsWith("GJB-"))
                //{
                //    r["型号规格"] = GeneralTools.GetString(r["型号规格"], string.Empty).Substring(4);
                //}
                r["型号规格"] = tmpdr["型号规格"];
                r["客户规格"] = tmpdr["客户规格"];
                r["执行标准"] = tmpdr["执行标准"];
                r["生产批号"] = tmpdr["生产批号"];
                r["生产日期"] = tmpdr["生产日期"];
                r["合同号"] = tmpdr["合同号"];
                if (iCount < iP)
                {
                    r["数量"] = iCount;
                }
                else
                {
                    r["数量"] = iP;
                }
                iCount -= iP;
                iPCount--;
                if (GeneralTools.GetDouble(tmpdr["淘汰率"], -1d) == -1)
                {
                    r["淘汰率"] = string.Empty;
                }
                else
                {
                    if (GeneralTools.GetDouble(tmpdr["淘汰率"], -1d) == 0d)
                    {
                        r["淘汰率"] = 0;
                    }
                    else
                    {
                        r["淘汰率"] = GeneralTools.GetString(tmpdr["淘汰率"], string.Empty) + "%";
                    }
                }
                if (GeneralTools.GetDouble(tmpdr["筛选数量"], -1d) == -1)
                {
                    r["筛选数量"] = string.Empty;
                }
                else
                {
                    r["筛选数量"] = GeneralTools.GetString(tmpdr["筛选数量"], string.Empty);
                }
                r["备注"] = tmpdr["备注"];
                r["包装员"] = tmpdr["包装员"];
                tmpdt_n.Rows.Add(r);
            }
            return tmpdt_n;
        }


        private DataTable GetReportData_n_ybp(DataRow tmpdr)
        {
            DataTable tmpdt_n = new DataTable();
            tmpdt_n.TableName = "ReportData";
            tmpdt_n.Columns.Add("型号规格");
            tmpdt_n.Columns.Add("客户规格");
            tmpdt_n.Columns.Add("执行标准");
            tmpdt_n.Columns.Add("生产批号");
            tmpdt_n.Columns.Add("生产日期");
            tmpdt_n.Columns.Add("合同号");
            tmpdt_n.Columns.Add("数量");
            tmpdt_n.Columns.Add("备注");
            tmpdt_n.Columns.Add("包装员");
            int iCount = GeneralTools.GetInt(tmpdr["提交数量"], 0);        //总数量
            int iP = GeneralTools.GetInt(tmpdr["内标签数量"], 0);             //内标签数量
            int iPCount = GeneralTools.GetInt(tmpdr["内标签张数"], 0);    //内标签张数
            while (iCount > 0 && iP > 0 && iPCount > 0)
            {
                DataRow r = tmpdt_n.NewRow();
                r["型号规格"] = tmpdr["型号规格"];
                r["客户规格"] = tmpdr["客户规格"];
                r["执行标准"] = tmpdr["执行标准"];
                r["生产批号"] = tmpdr["生产批号"];
                r["生产日期"] = tmpdr["生产日期"];
                r["合同号"] = tmpdr["合同号"];
                if (iCount < iP)
                {
                    r["数量"] = iCount;
                }
                else
                {
                    r["数量"] = iP;
                }
                iCount -= iP;
                iPCount--;
                r["备注"] = tmpdr["备注"];
                r["包装员"] = tmpdr["包装员"];
                tmpdt_n.Rows.Add(r);
            }
            return tmpdt_n;
        }

        private void iniPrinterSettings()
        {
            if (dtPrinterSettings == null)
            {
                dtPrinterSettings = new DataTable();
                dtPrinterSettings.Columns.Add("模板");
                dtPrinterSettings.Columns.Add("指定打印机");
            }
            else
            {
                dtPrinterSettings.Rows.Clear();
            }
            if (Properties.Settings.Default.PrinterSettings.Length > 0)
            {
                string[] tmpSettings = Properties.Settings.Default.PrinterSettings.Split(';');
                if (tmpSettings.Length % 2 != 0)
                {
                    MessageBox.Show("打印机设置有误，请检查后重新设置！", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    this.Close();
                }
                DataRow r;
                for (int i = 0; i < tmpSettings.Length - 1; i += 2)
                {
                    r = dtPrinterSettings.NewRow();
                    r["模板"] = tmpSettings[i];
                    r["指定打印机"] = tmpSettings[i + 1];
                    dtPrinterSettings.Rows.Add(r);
                }
            }
        }

        private int GetSettingIndex(string strTempletName)
        {
            int ret = -1;
            for (int i = 0; i < dtPrinterSettings.Rows.Count; i++)
            {
                if (dtPrinterSettings.Rows[i]["模板"].ToString() == strTempletName)
                {
                    ret = i;
                    break;
                }
            }
            return ret;
        }

        /// <summary>
        /// 返回产品包装数量
        /// </summary>
        /// <param name="strClass">质量等级</param>
        /// <param name="strModel">型号</param>
        /// <param name="strSize">尺寸</param>
        /// <param name="bBD">尺寸</param>
        /// <returns>包装数量</returns>
        private int GetPackingQuantity(string strClass, string strModel, string strSize, bool bBD)
        {
            string strTmpSelectString = "select 包装数量 from 产品尺寸与包装数量表 where 编带='" + GeneralTools.GetString(bBD, string.Empty) + "'";
            DataTable tmpdt = new DataTable();
            //查找有无符合全部条件的项
            tmpdt = sqt.GetData(strTmpSelectString + " and 质量等级='" + strClass + "' and 型号='" + strModel + "' and 尺寸='" + strSize + "'");
            if (tmpdt.Rows.Count > 0)
            {
                return GeneralTools.GetInt(tmpdt.Rows[0]["包装数量"], -1);
            }
            else
            {
                //如果没有符合全部条件的项，则搜索是否有忽略其中一个条件的项
                tmpdt = sqt.GetData(strTmpSelectString + " and (质量等级='忽略等级' and 型号='" + strModel + "' and 尺寸='" + strSize + "') or " +
                                                                                      "(质量等级='" + strClass + "' and 型号='忽略型号' and 尺寸='" + strSize + "') or " +
                                                                                      "(质量等级='" + strClass + "' and 型号='" + strModel + "' and 尺寸='忽略尺寸')");
                if (tmpdt.Rows.Count > 0)
                {
                    return GeneralTools.GetInt(tmpdt.Rows[0]["包装数量"], -1);
                }
                else
                {
                    //如果没有符合忽略其中一个条件的项，搜索是否有忽略其中两个条件的项
                    tmpdt = sqt.GetData(strTmpSelectString + " and (质量等级='忽略等级' and 型号='忽略型号' and 尺寸='" + strSize + "') or " +
                                                                                      "(质量等级='" + strClass + "' and 型号='忽略型号' and 尺寸='忽略尺寸') or " +
                                                                                      "(质量等级='忽略等级' and 型号='" + strModel + "' and 尺寸='忽略尺寸')");
                    if (tmpdt.Rows.Count > 0)
                    {
                        return GeneralTools.GetInt(tmpdt.Rows[0]["包装数量"], -1);
                    }
                    else
                    {
                        return -1;
                    }
                }
            }
            return 0;
        }

        private void CheckDataToChangeColor()
        {
            if (dgv1.Rows.Count > 0)
            {
                for (int i = 0; i < dgv1.Rows.Count; i++)
                {
                    if (GeneralTools.GetInt(dgv1.Rows[i].Cells["内标签张数"].Value, 0) == 0)
                    {
                        dgv1.Rows[i].Cells["内标签张数"].Style.BackColor = Color.Yellow;
                    }
                    else
                    {
                        if (GeneralTools.GetInt(dgv1.Rows[i].Cells["内标签张数"].Value, 0) < 0)
                        {
                            dgv1.Rows[i].Cells["内标签张数"].Style.BackColor = Color.Red;
                        }
                        else
                        {
                            dgv1.Rows[i].Cells["内标签张数"].Style.BackColor = Color.White;
                        }
                    }
                }
            }
        }

        private void chkManualMode_CheckedChanged(object sender, EventArgs e)
        {
            dgv1.ReadOnly = !chkManualMode.Checked;
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (dgv1.CurrentRow == null)
            {
                GeneralTools.ShowInfoMsg("请先选择要预览的行！");
                return;
            }
            DataTable dt = (DataTable)dgv1.DataSource;
            DataSet ds = new DataSet();
            DataTable tmpdt = new DataTable();
            bool b43 = false;
            bool b14 = false;
            DataTable dtCustomer = sqt.GetData("select hta003 客户编号,hta004 客户名称 from TPAMain.dbo.hta_table where hta001='" + GeneralTools.GetString(dt.Rows[0]["订单编号"], string.Empty) + "'");
            if (dtCustomer.Rows.Count > 0)
            {
                string strTmpCustomerID = GeneralTools.GetString(dtCustomer.Rows[0]["客户编号"], string.Empty);
                string strTmpCustomerName = GeneralTools.GetString(dtCustomer.Rows[0]["客户名称"], string.Empty);
                if (strTmpCustomerID.StartsWith("43") || strTmpCustomerID.StartsWith("08-43"))
                {
                    b43 = true;
                }
                if (strTmpCustomerID.StartsWith("08-14") &&
                    (!strTmpCustomerName.Equals("中电科技（南京）电子信息发展有限公司")))
                {
                    b14 = true;
                }
            }
            //默认
            //仅内标签
            //仅外标签
            //外标签
            if (cmbPrintMode.SelectedIndex == 0 || cmbPrintMode.SelectedIndex == 2)
            {
                //if (GeneralTools.GetString(dgv1.CurrentRow.Cells["型号规格"].Value, string.Empty).StartsWith("M-") ||
                //    GeneralTools.GetString(dgv1.CurrentRow.Cells["型号规格"].Value, string.Empty).StartsWith("J-"))
                //{
                //    tmpdt = GetReportData_w_ybp(dt.Rows[dgv1.CurrentRow.Index]);
                //}
                //else
                //{
                //    tmpdt = GetReportData_w_qz(dt.Rows[dgv1.CurrentRow.Index]);
                //}
                #region 检查是否是43所客户编号，如果是，则打印外标签前先打印43所指定的二维码
                if (b43)
                {
                    tmpdt = GetReportData_w_43(dt.Rows[dgv1.CurrentRow.Index]);
                    if (tmpdt.Rows.Count == 0)
                    {
                        GeneralTools.ShowWarningMsg("第" + GeneralTools.GetString(dgv1.CurrentRow.Index + 1, string.Empty) + "条报表数据解析错误！");
                    }
                    else
                    {
                        string strReportFileName = Application.StartupPath + "\\template\\外标签_43所.rpt";
                        if (!File.Exists(strReportFileName))
                        {
                            GeneralTools.ShowErrorMsg("43所二维码外标签打印模板不存在！");
                            return;
                        }
                        else
                        {
                            ds.Tables.Clear();
                            ds.Tables.Add(tmpdt);
                            reportpreviewFrm newReportPreviewFrm = new reportpreviewFrm(ds, strReportFileName);
                            newReportPreviewFrm.ShowDialog();
                        }
                    }
                }
                #endregion
                tmpdt = GetReportData_w(dt.Rows[dgv1.CurrentRow.Index]);
                if (tmpdt.Rows.Count == 0)
                {
                    GeneralTools.ShowWarningMsg("报表数据解析错误！");
                    return;
                }
                else
                {
                    string strReportFileName = string.Empty;
                    if (b14)
                    {
                        strReportFileName = Application.StartupPath + "\\template\\外标签_通用2.rpt";
                    }
                    else if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("GJB"))
                    {
                        strReportFileName = Application.StartupPath + "\\template\\外标签_国军标.rpt";
                    }
                    else
                    {
                        //strReportFileName = Application.StartupPath + "\\template\\外标签_二维码.rpt";
                        if (GeneralTools.GetChineseTextLength(GeneralTools.GetString(dgv1.CurrentRow.Cells["备注"].Value, string.Empty)) > 48)
                        {
                            strReportFileName = Application.StartupPath + "\\template\\外标签_二维码_小字.rpt";
                        }
                        else
                        {
                            strReportFileName = Application.StartupPath + "\\template\\外标签_二维码.rpt";
                        }
                    }
                    if (chkWbq.Checked && cmbWbq.SelectedIndex >= 0)
                    {
                        strReportFileName = Application.StartupPath + "\\template\\Special\\" + cmbWbq.Text + ".rpt";
                    }
                    if (!File.Exists(strReportFileName))
                    {
                        GeneralTools.ShowErrorMsg("外标签打印模板不存在！");
                        return;
                    }
                    else
                    {
                        ds.Tables.Clear();
                        #region 处理超长的备注
                        int iMemoWidth = 0;
                        if (strReportFileName.Contains("小字"))
                        {
                            iMemoWidth = 17;
                        }
                        else
                        {
                            iMemoWidth = 15;
                        }
                        string strTmpMemo = GeneralTools.GetString(tmpdt.Rows[0]["备注"], string.Empty);
                        StringBuilder tmpsb = new StringBuilder();
                        string strTmp = string.Empty;
                        for (int i = 0; i < strTmpMemo.Length; i++)
                        {
                            int iTmp = 1;
                            if (GeneralTools.IsChineseChar(strTmpMemo[i]))
                            {
                                iTmp = 2;
                            }
                            if (GeneralTools.GetChineseTextLength(strTmp) + iTmp > iMemoWidth)
                            {
                                tmpsb.Append(strTmp + "\n");
                                strTmp = string.Empty;
                                strTmp += strTmpMemo[i];
                                continue;
                            }
                            if (GeneralTools.GetChineseTextLength(strTmp) + iTmp == iMemoWidth)
                            {
                                strTmp += strTmpMemo[i];
                                tmpsb.Append(strTmp + "\n");
                                strTmp = string.Empty;
                                continue;
                            }
                            if (GeneralTools.GetChineseTextLength(strTmp) + iTmp < iMemoWidth)
                            {
                                strTmp += strTmpMemo[i];
                                if (i == strTmpMemo.Length - 1)
                                {
                                    tmpsb.Append(strTmp);
                                }
                                continue;
                            }
                        }
                        tmpdt.Rows[0]["备注"] = tmpsb.ToString();
                        #endregion
                        ds.Tables.Add(tmpdt);
                        reportpreviewFrm newReportPreviewFrm = new reportpreviewFrm(ds, strReportFileName);
                        newReportPreviewFrm.ShowDialog();
                    }
                }
            }
            //内标签
            if (cmbPrintMode.SelectedIndex == 0 || cmbPrintMode.SelectedIndex == 1)
            {
                //检查是否是43所客户编号且质量等级为普军，如果是，则调用七专数据
                if (b43 && dgv1.CurrentRow.Cells["质量等级"].Value.Equals("J"))
                {
                    tmpdt = GetReportData_n_qz(dt.Rows[dgv1.CurrentRow.Index]);
                }
                else
                {
                    if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("M") ||
                        dgv1.CurrentRow.Cells["质量等级"].Value.Equals("J"))
                    {
                        tmpdt = GetReportData_n_ybp(dt.Rows[dgv1.CurrentRow.Index]);
                    }
                    else
                    {
                        tmpdt = GetReportData_n_qz(dt.Rows[dgv1.CurrentRow.Index]);
                    }
                }
                if (tmpdt.Rows.Count == 0)
                {
                    GeneralTools.ShowWarningMsg("报表数据解析错误！");
                    return;
                }
                else
                {
                    string strReportFileName = string.Empty;
                    //检查是否是43所客户编号且质量等级为普军，如果是，则调用七专模板
                    if (b43 && dgv1.CurrentRow.Cells["质量等级"].Value.Equals("J"))
                    {
                        strReportFileName = Application.StartupPath + "\\template\\内标签_七专.rpt";
                    }
                    else
                    {
                        if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("M") ||
                        dgv1.CurrentRow.Cells["质量等级"].Value.Equals("J"))
                        {
                            if (b14)
                            {
                                strReportFileName = Application.StartupPath + "\\template\\内标签_一般品2.rpt";
                            }
                            else
                            {
                                strReportFileName = Application.StartupPath + "\\template\\内标签_一般品.rpt";
                            }
                        }
                        else
                        {
                            if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("GJB"))
                            {
                                strReportFileName = Application.StartupPath + "\\template\\内标签_国军标.rpt";
                            }
                            else
                            {
                                if (b14)
                                {
                                    strReportFileName = Application.StartupPath + "\\template\\内标签_七专2.rpt";
                                }
                                else
                                {
                                    strReportFileName = Application.StartupPath + "\\template\\内标签_七专.rpt";
                                }
                            }
                        }
                    }
                    if (chkNbq.Checked && cmbNbq.SelectedIndex >= 0)
                    {
                        strReportFileName = Application.StartupPath + "\\template\\Special\\" + cmbNbq.Text + ".rpt";
                    }
                    if (!File.Exists(strReportFileName))
                    {
                        GeneralTools.ShowErrorMsg("外标签打印模板不存在！");
                        return;
                    }
                    else
                    {
                        ds.Tables.Clear();
                        ds.Tables.Add(tmpdt);
                        reportpreviewFrm newReportPreviewFrm = new reportpreviewFrm(ds, strReportFileName);
                        newReportPreviewFrm.ShowDialog();
                    }
                }
            }
        }

        private void dgv1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (dgv1.CurrentCell != null && e.ColumnIndex == 0)
            {
                if (GeneralTools.GetInt(dgv1.Rows[e.RowIndex].Cells["外标签数量"].Value, 0) == 0)
                {
                    dgv1.Rows[e.RowIndex].Cells["外标签张数"].Value = 0;
                }
                else
                {
                    try
                    {
                        dgv1.Rows[e.RowIndex].Cells["外标签张数"].Value = Math.Ceiling(GeneralTools.GetDouble(dgv1.Rows[e.RowIndex].Cells["提交数量"].Value, 0d) / GeneralTools.GetDouble(dgv1.Rows[e.RowIndex].Cells["外标签数量"].Value, 0d));
                    }
                    catch
                    {
                        dgv1.Rows[e.RowIndex].Cells["外标签张数"].Value = 0;
                    }
                }
                CheckDataToChangeColor();
            }
            if (dgv1.CurrentCell != null && e.ColumnIndex == 2)
            {
                if (GeneralTools.GetInt(dgv1.Rows[e.RowIndex].Cells["内标签数量"].Value, 0) == 0)
                {
                    dgv1.Rows[e.RowIndex].Cells["内标签张数"].Value = 0;
                }
                else
                {
                    try
                    {
                        dgv1.Rows[e.RowIndex].Cells["内标签张数"].Value = Math.Ceiling(GeneralTools.GetDouble(dgv1.Rows[e.RowIndex].Cells["提交数量"].Value, 0d) / GeneralTools.GetDouble(dgv1.Rows[e.RowIndex].Cells["内标签数量"].Value, 0d));
                    }
                    catch
                    {
                        dgv1.Rows[e.RowIndex].Cells["内标签张数"].Value = 0;
                    }
                }
                CheckDataToChangeColor();
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (dgv1.Rows.Count == 0)
            {
                GeneralTools.ShowInfoMsg("没有可供打印的数据！");
                return;
            }
            DataTable dt = (DataTable)dgv1.DataSource;
            DataSet ds = new DataSet();
            DataTable tmpdt = new DataTable();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                #region 检查产品是否是四川华丰专用，但提交合同不是华丰合同
                //获取客户编号
                string strTmpCustomer = GeneralTools.GetString(sqt.DoCmdScalarData("select hta003 from TPAMain.dbo.hta_table where hta001='" + GeneralTools.GetString(dt.Rows[i]["订单编号"], string.Empty) + "'"), string.Empty);
                //获取工序结余备注
                string strTmpGxjyMemo = GeneralTools.GetString(sqt.DoCmdScalarData("select gxjy015 from DefualtDataBase .dbo .QZKFC ,TPAMain .dbo .gxck_table,TPAMain .dbo .gxjy_table where 出库单号 collate Chinese_PRC_BIN=gxck001 and gxck007=gxjy001 and 序号='" + GeneralTools.GetString(dt.Rows[i]["提交序号"], string.Empty) + "'"), string.Empty);
                if ((!strTmpCustomer.StartsWith("SCHF")) && strTmpGxjyMemo.Contains("华丰"))
                {
                    GeneralTools.ShowErrorMsg("第" + Convert.ToString(i + 1) + "项是四川华丰专用产品，不能用于发放其它用户的订单，请检查！");
                    return;
                }
                #endregion
            }
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                bool b43 = false;
                bool b14 = false;
                DataTable dtCustomer = sqt.GetData("select hta003 客户编号,hta004 客户名称 from TPAMain.dbo.hta_table where hta001='" + GeneralTools.GetString(dt.Rows[i]["订单编号"], string.Empty) + "'");
                if (dtCustomer.Rows.Count > 0)
                {
                    string strTmpCustomerID = GeneralTools.GetString(dtCustomer .Rows [0]["客户编号"], string.Empty);
                    string strTmpCustomerName= GeneralTools.GetString(dtCustomer.Rows[0]["客户名称"], string.Empty);
                    if (strTmpCustomerID.StartsWith("43") || strTmpCustomerID.StartsWith("08-43"))
                    {
                        b43 = true;
                    }
                    if (strTmpCustomerID.StartsWith("08-14") &&
                        (!strTmpCustomerName.Equals ("中电科技（南京）电子信息发展有限公司")))
                    {
                        b14 = true;
                    } }
                #region 外标签
                if (cmbPrintMode.SelectedIndex == 0 || cmbPrintMode.SelectedIndex == 2)
                {
                    #region 检查是否是43所客户编号，如果是，则打印外标签前先打印43所指定的二维码
                    if (b43)
                    {
                        tmpdt = GetReportData_w_43(dt.Rows[i]);
                        if (tmpdt.Rows.Count == 0)
                        {
                            GeneralTools.ShowWarningMsg("第" + GeneralTools.GetString(i + 1, string.Empty) + "条报表数据解析错误！");
                        }
                        else
                        {
                            string strReportFileName = Application.StartupPath + "\\template\\外标签_43所.rpt";
                            if (!File.Exists(strReportFileName))
                            {
                                GeneralTools.ShowErrorMsg("43所二维码外标签打印模板不存在！");
                                return;
                            }
                            else
                            {
                                ds.Tables.Clear();
                                ds.Tables.Add(tmpdt);
                                ReportDocument rd = new ReportDocument();
                                rd.Load(strReportFileName);
                                FileInfo fi = new FileInfo(strReportFileName);
                                int ind = GetSettingIndex(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));
                                if (ind != -1)
                                {
                                    rd.PrintOptions.PrinterName = dtPrinterSettings.Rows[ind]["指定打印机"].ToString();
                                }
                                rd.SetDataSource(ds);
                                while (!rd.IsLoaded)
                                { }
                                try
                                {
                                    rd.PrintToPrinter(1, false, 0, 0);
                                }
                                catch (Exception ex)
                                {
                                    MessageBox.Show(ex.Message);
                                }
                                finally
                                {
                                    rd.Dispose();
                                }
                            }
                        }
                    }
                    #endregion
                    //获取外标签数据集
                    tmpdt = GetReportData_w(dt.Rows[i]);
                    if (tmpdt.Rows.Count == 0)
                    {
                        GeneralTools.ShowWarningMsg("第" + GeneralTools.GetString(i + 1, string.Empty) + "条报表数据解析错误！");
                    }
                    else
                    {
                        string strReportFileName = string.Empty;
                        #region 加载模板名称
                        //根据质量等级和备注长度决定标签样式
                        if (b14)
                        {
                            strReportFileName = Application.StartupPath + "\\template\\外标签_通用2.rpt";
                        }
                        else if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("GJB"))
                        {
                            strReportFileName = Application.StartupPath + "\\template\\外标签_国军标.rpt";
                        }
                        else
                        {
                            if (GeneralTools.GetString(dt.Rows[i]["备注"], string.Empty).Length > 40)
                            {
                                strReportFileName = Application.StartupPath + "\\template\\外标签_二维码_小字.rpt";
                            }
                            else
                            {
                                strReportFileName = Application.StartupPath + "\\template\\外标签_二维码.rpt";
                            }
                        }
                        //如果选择了特殊模板，则直接调用指定的模板
                        if (chkWbq.Checked && cmbWbq.SelectedIndex >= 0)
                        {
                            strReportFileName = Application.StartupPath + "\\template\\Special\\" + cmbWbq.Text + ".rpt";
                        }
                        #endregion
                        if (!File.Exists(strReportFileName))
                        {
                            GeneralTools.ShowErrorMsg("外标签打印模板不存在！");
                            return;
                        }
                        else
                        {
                            #region 打印
                            ds.Tables.Clear();
                            #region 处理超长的备注
                            int iMemoWidth = 0;
                            if (strReportFileName.Contains("小字"))
                            {
                                iMemoWidth = 17;
                            }
                            else
                            {
                                iMemoWidth = 15;
                            }
                            string strTmpMemo = GeneralTools.GetString(tmpdt.Rows[0]["备注"], string.Empty);
                            StringBuilder tmpsb = new StringBuilder();
                            string strTmp = string.Empty;
                            for (int k = 0; k < strTmpMemo.Length; k++)
                            {
                                int iTmp = 1;
                                if (GeneralTools.IsChineseChar(strTmpMemo[k]))
                                {
                                    iTmp = 2;
                                }
                                if (GeneralTools.GetChineseTextLength(strTmp) + iTmp > iMemoWidth)
                                {
                                    tmpsb.Append(strTmp + "\n");
                                    strTmp = string.Empty;
                                    strTmp += strTmpMemo[k];
                                    continue;
                                }
                                if (GeneralTools.GetChineseTextLength(strTmp) + iTmp == iMemoWidth)
                                {
                                    strTmp += strTmpMemo[k];
                                    tmpsb.Append(strTmp + "\n");
                                    strTmp = string.Empty;
                                    continue;
                                }
                                if (GeneralTools.GetChineseTextLength(strTmp) + iTmp < iMemoWidth)
                                {
                                    strTmp += strTmpMemo[k];
                                    if (k == strTmpMemo.Length - 1)
                                    {
                                        tmpsb.Append(strTmp);
                                    }
                                    continue;
                                }
                            }
                            tmpdt.Rows[0]["备注"] = tmpsb.ToString();
                            #endregion
                            ds.Tables.Add(tmpdt);
                            ReportDocument rd = new ReportDocument();
                            rd.Load(strReportFileName);
                            FileInfo fi = new FileInfo(strReportFileName);
                            int ind = GetSettingIndex(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));
                            if (chkWbq.Checked && cmbWbq.SelectedIndex >= 0)
                            {
                                ind = GetSettingIndex(cmbWbq.Text);
                            }
                            if (ind != -1)
                            {
                                rd.PrintOptions.PrinterName = dtPrinterSettings.Rows[ind]["指定打印机"].ToString();
                            }
                            rd.SetDataSource(ds);
                            while (!rd.IsLoaded)
                            { }
                            try
                            {
                                rd.PrintToPrinter(1, false, 0, 0);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            finally
                            {
                                rd.Dispose();
                            }
                            #endregion
                        }
                    }
                }
                #endregion
                #region  内标签
                if (cmbPrintMode.SelectedIndex == 0 || cmbPrintMode.SelectedIndex == 1)
                {
                    #region 加载数据
                    //如果是43所产品，且质量等级为普军，则调用七专数据
                    if (b43 && dt.Rows[i]["质量等级"].Equals("J"))
                    {
                        tmpdt = GetReportData_n_qz(dt.Rows[i]);
                    }
                    else
                    {
                        if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("M") ||
                            dgv1.CurrentRow.Cells["质量等级"].Value.Equals("J"))
                        {
                            tmpdt = GetReportData_n_ybp(dt.Rows[i]);
                        }
                        else
                        {
                            tmpdt = GetReportData_n_qz(dt.Rows[i]);
                        }
                    }
                    #endregion
                    if (tmpdt.Rows.Count == 0)
                    {
                        GeneralTools.ShowWarningMsg("报表数据解析错误！");
                        return;
                    }
                    else
                    {
                        string strReportFileName = string.Empty;
                        #region 加载模板名称
                        //如果是43所产品，且质量等级为普军，则调用七专模板
                        if (b43 && dt.Rows[i]["质量等级"].Equals("J"))
                        {
                            strReportFileName = Application.StartupPath + "\\template\\内标签_七专.rpt";
                        }
                        else
                        {
                            if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("M") ||
                                dgv1.CurrentRow.Cells["质量等级"].Value.Equals("J"))
                            {
                                if (b14)
                                {
                                    strReportFileName = Application.StartupPath + "\\template\\内标签_一般品2.rpt";
                                }
                                else
                                {
                                    strReportFileName = Application.StartupPath + "\\template\\内标签_一般品.rpt";
                                }
                            }
                            else
                            {
                                if (dgv1.CurrentRow.Cells["质量等级"].Value.Equals("GJB"))
                                {
                                    strReportFileName = Application.StartupPath + "\\template\\内标签_国军标.rpt";
                                }
                                else
                                {
                                    if (b14)
                                    {
                                        strReportFileName = Application.StartupPath + "\\template\\内标签_七专2.rpt";
                                    }
                                    else
                                    {
                                        strReportFileName = Application.StartupPath + "\\template\\内标签_七专.rpt";
                                    }
                                }
                            }
                        }
                        if (chkNbq.Checked && cmbNbq.SelectedIndex >= 0)
                        {
                            strReportFileName = Application.StartupPath + "\\template\\Special\\" + cmbNbq.Text + ".rpt";
                        }
                        #endregion
                        if (!File.Exists(strReportFileName))
                        {
                            GeneralTools.ShowErrorMsg("内标签打印模板不存在！");
                            return;
                        }
                        else
                        {
                            #region 打印
                            ds.Tables.Clear();
                            ds.Tables.Add(tmpdt);
                            ReportDocument rd = new ReportDocument();
                            rd.Load(strReportFileName);
                            FileInfo fi = new FileInfo(strReportFileName);
                            int ind = GetSettingIndex(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));
                            if (chkNbq.Checked && cmbNbq.SelectedIndex >= 0)
                            {
                                ind = GetSettingIndex(cmbNbq.Text);
                            }
                            if (ind != -1)
                            {
                                rd.PrintOptions.PrinterName = dtPrinterSettings.Rows[ind]["指定打印机"].ToString();
                            }
                            rd.SetDataSource(ds);
                            while (!rd.IsLoaded)
                            { }
                            try
                            {
                                rd.PrintToPrinter(1, false, 0, 0);
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.Message);
                            }
                            finally
                            {
                                rd.Dispose();
                            }
                            #endregion
                        }
                    }
                }
                #endregion
            }
            #region 打印607订单号标签
            //if (cmbPrintMode.SelectedIndex  == 0 || cmbPrintMode.SelectedIndex  == 2)
            //{
            //    //获取DatagridView数据源
            //    DataTable tmpdt2 = (DataTable)dgv1.DataSource;
            //    //筛选出唯一的订单编号与订单项次
            //    DataView tmpdv = tmpdt2.DefaultView;
            //    tmpdt2 = tmpdv.ToTable(true, new string[] { "订单编号","订单项次"});
            //    //拼接查询脚本
            //    if (tmpdt2.Rows.Count >0)
            //    {
            //        string strTmpSelect607OrderID = "select distinct replace(REPLACE (htb027,'需方订单号',''),' ','') 订单号 from TPAMain.dbo.hta_table ,TPAMain.dbo.htb_table where hta001=htb001 and hta014='Y' and hta003 like '607%' and htb027<>'' and (";
            //        for (int i=0;i<tmpdt2.Rows.Count;i++)
            //        {
            //            strTmpSelect607OrderID += "(htb001='" + GeneralTools.GetString(tmpdt2.Rows[i]["订单编号"], string.Empty) + "' and htb002=" + GeneralTools.GetInt(tmpdt2.Rows[i]["订单项次"], 0).ToString() + ")";
            //            if (i<tmpdt2.Rows.Count -1)
            //            {
            //                strTmpSelect607OrderID += " or ";
            //            }
            //        }
            //        strTmpSelect607OrderID += ")";
            //        //获取需方订单号
            //        tmpdt2 = sqt.GetData(strTmpSelect607OrderID);
            //        if (tmpdt2.Rows.Count  >0)
            //        {
            //            DataTable tmpdt3 = new DataTable();
            //            tmpdt3.Columns.Add("订单号");
            //            tmpdt3.Columns.Add("二维码", typeof(System.Byte[]));
            //            tmpdt3.TableName = "ReportData";
            //            for (int i = 0; i < tmpdt2.Rows.Count; i++)
            //            {
            //                if (GeneralTools.GetString(tmpdt2.Rows[i]["订单号"], string.Empty).Equals(string.Empty))
            //                {
            //                    //如果需方订单号为空的话，则不打印标签
            //                    continue;
            //                }
            //                DataRow r = tmpdt3.NewRow();
            //                r["订单号"] = tmpdt2.Rows[i]["订单号"];
            //                try
            //                {
            //                    QRCodeEncoder qc = new QRCodeEncoder();
            //                    qc.QRCodeEncodeMode = QRCodeEncoder.ENCODE_MODE.BYTE;
            //                    //Size
            //                    qc.QRCodeScale = 4;
            //                    //Version
            //                    qc.QRCodeVersion = 2;
            //                    //CorrectLevel
            //                    qc.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.L;
            //                    Image image = qc.Encode(GeneralTools.GetString(tmpdt2.Rows[i]["订单号"], string.Empty));
            //                    System.IO.MemoryStream ms = new System.IO.MemoryStream();
            //                    image.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            //                    r["二维码"] = ms.GetBuffer();
            //                }
            //                catch
            //                {
            //                }
            //                tmpdt3.Rows.Add(r);
            //            }
            //            //初始化标签模板文件名称
            //            string strReportFileName = Application.StartupPath + "\\template\\607订单号标签.rpt";
            //            if (!File.Exists (strReportFileName ))
            //            {
            //                GeneralTools.ShowErrorMsg("607订单号标签打印模板不存在，请联系管理员处理！");
            //                return;
            //            }
            //            //加载数据
            //            DataSet tmpds = new DataSet();
            //            tmpds.Tables.Add(tmpdt3);
            //            //加载打印模板
            //            ReportDocument rd = new ReportDocument();
            //            rd.Load(strReportFileName);
            //            FileInfo fi = new FileInfo(strReportFileName);
            //            int ind = GetSettingIndex(fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length));
            //            if (ind != -1)
            //            {
            //                rd.PrintOptions.PrinterName = dtPrinterSettings.Rows[ind]["指定打印机"].ToString();
            //            }
            //            rd.SetDataSource(tmpds);
            //            while (!rd.IsLoaded)
            //            { }
            //            try
            //            {
            //                rd.PrintToPrinter(1, false, 0, 0);
            //            }
            //            catch (Exception ex)
            //            {
            //                MessageBox.Show(ex.Message);
            //            }
            //            finally
            //            {
            //                rd.Dispose();
            //            }
            //        }
            //    }
            //}
            #endregion
        }

        private void tsmiMemoAdd_xq_Click(object sender, EventArgs e)
        {
            if (dgv1.SelectedRows.Count > 0)
            {
                for (int i = 0; i < dgv1.SelectedRows.Count; i++)
                {
                    dgv1.SelectedRows[i].Cells["备注"].Value = GeneralTools.GetString(dgv1.SelectedRows[i].Cells["备注"].Value, string.Empty) + " 锡铅";
                }
            }
        }

        private void tsmiCopy_Click(object sender, EventArgs e)
        {
            if (dgv1.SelectedCells.Count > 0)
            {
                DataGridClipBoard = dgv1.SelectedCells;
            }
        }

        private void tsmiPaste_Click(object sender, EventArgs e)
        {
            if (DataGridClipBoard != null && dgv1.SelectedCells.Count > 0 && chkManualMode.Checked)
            {
                foreach (DataGridViewCell dgvc in dgv1.SelectedCells)
                {
                    foreach (DataGridViewCell dgvc2 in DataGridClipBoard)
                    {
                        if (dgvc.ColumnIndex < 4)
                        {
                            continue;
                        }
                        if (dgvc.ColumnIndex == dgvc2.ColumnIndex)
                        {
                            dgvc.Value = dgvc2.Value;
                            break;
                        }
                    }
                }
                dgv1.EndEdit();
            }
        }

        private void tsmiClear_Click(object sender, EventArgs e)
        {
            if (chkManualMode.Checked)
            {
                foreach (DataGridViewCell dgvc in dgv1.SelectedCells)
                {
                    if (dgvc.ColumnIndex < 4)
                    {
                        continue;
                    }
                    dgvc.Value = string.Empty;
                }
            }
        }

        private void chkWbq_CheckedChanged(object sender, EventArgs e)
        {
            cmbWbq.Enabled = chkWbq.Checked;
        }

        private void chkNbq_CheckedChanged(object sender, EventArgs e)
        {
            cmbNbq.Enabled = chkNbq.Checked;
        }
    }
}